'use client';

import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Table, Select, Input, Button, Tabs, Spin, message, Typography, DatePicker, Tooltip } from 'antd';
import { SearchOutlined, ReloadOutlined, BarChartOutlined, LineChartOutlined, PieChartOutlined, InfoCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import Layout from '@/components/Layout';
import { 
  getRecruitStatistics, 
  getRecruitStatisticsByType, 
  getRecruitStatisticsByPlanId,
  getInterviewStatistics,
  getInterviewStatisticsByType,
  getInterviewStatisticsByPlanId,
  RecruitStatisticsItem,
  InterviewStatisticsItem
} from '@/lib/statistic';

// 导入图表组件
import ReactECharts from 'echarts-for-react';
import type { EChartsOption } from 'echarts';
// 导入Excel导出工具
import * as XLSX from 'xlsx';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

const RecruitmentAnalyticsPage = () => {
  // 状态定义
  const [activeTab, setActiveTab] = useState('recruitRate');
  const [loading, setLoading] = useState(false);
  const [planType, setPlanType] = useState<number | undefined>(undefined);
  const [planId, setPlanId] = useState<number | undefined>(undefined);
  const [searchText, setSearchText] = useState('');
  
  // 面试筛选条件
  const [interviewId, setInterviewId] = useState<number | undefined>(undefined);
  const [deptId, setDeptId] = useState<string | undefined>(undefined);
  const [positionNumber, setPositionNumber] = useState<string | undefined>(undefined);
  
  // 招聘计划转化率数据
  const [recruitStats, setRecruitStats] = useState<RecruitStatisticsItem[]>([]);
  const [recruitTotal, setRecruitTotal] = useState(0);
  const [recruitPage, setRecruitPage] = useState(1);
  const [recruitPageSize, setRecruitPageSize] = useState(10);
  
  // 面试通过率数据
  const [interviewStats, setInterviewStats] = useState<InterviewStatisticsItem[]>([]);
  const [interviewTotal, setInterviewTotal] = useState(0);
  const [interviewPage, setInterviewPage] = useState(1);
  const [interviewPageSize, setInterviewPageSize] = useState(10);

  // 招聘计划转化率表格列定义
  const recruitColumns = [
    {
      title: '计划ID',
      dataIndex: 'planId',
      key: 'planId',
      width: 100,
    },
    {
      title: '计划名称',
      dataIndex: 'planName',
      key: 'planName',
      width: 200,
    },
    {
      title: '招聘人数',
      dataIndex: 'allRecruitsNumber',
      key: 'allRecruitsNumber',
      width: 120,
      sorter: (a: RecruitStatisticsItem, b: RecruitStatisticsItem) => a.allRecruitsNumber - b.allRecruitsNumber,
    },
    {
      title: '申请人数',
      dataIndex: 'allApplicantNumber',
      key: 'allApplicantNumber',
      width: 120,
      sorter: (a: RecruitStatisticsItem, b: RecruitStatisticsItem) => a.allApplicantNumber - b.allApplicantNumber,
    },
    {
      title: '通过人数',
      dataIndex: 'allThroughNumber',
      key: 'allThroughNumber',
      width: 120,
      sorter: (a: RecruitStatisticsItem, b: RecruitStatisticsItem) => a.allThroughNumber - b.allThroughNumber,
    },
    {
      title: '转化率',
      dataIndex: 'allConversionRate',
      key: 'allConversionRate',
      width: 120,
      sorter: (a: RecruitStatisticsItem, b: RecruitStatisticsItem) => {
        const rateA = parseFloat(a.allConversionRate.replace('%', ''));
        const rateB = parseFloat(b.allConversionRate.replace('%', ''));
        return rateA - rateB;
      },
      render: (text: string) => <span style={{ color: parseFloat(text) > 50 ? '#52c41a' : '#f5222d' }}>{text}</span>,
    },
  ];

  // 面试通过率表格列定义
  const interviewColumns = [
    {
      title: '面试ID',
      dataIndex: 'interviewId',
      key: 'interviewId',
      width: 100,
    },
    {
      title: '面试名称',
      dataIndex: 'interviewName',
      key: 'interviewName',
      width: 200,
    },
    {
      title: '招聘人数',
      dataIndex: 'recruitsNumber',
      key: 'recruitsNumber',
      width: 120,
      sorter: (a: InterviewStatisticsItem, b: InterviewStatisticsItem) => a.recruitsNumber - b.recruitsNumber,
    },
    {
      title: '申请人数',
      dataIndex: 'applicantNumber',
      key: 'applicantNumber',
      width: 120,
      sorter: (a: InterviewStatisticsItem, b: InterviewStatisticsItem) => a.applicantNumber - b.applicantNumber,
    },
    {
      title: '通过人数',
      dataIndex: 'throughNumber',
      key: 'throughNumber',
      width: 120,
      sorter: (a: InterviewStatisticsItem, b: InterviewStatisticsItem) => a.throughNumber - b.throughNumber,
    },
    {
      title: '转化率',
      dataIndex: 'conversionRate',
      key: 'conversionRate',
      width: 120,
      sorter: (a: InterviewStatisticsItem, b: InterviewStatisticsItem) => {
        const rateA = parseFloat(a.conversionRate.replace('%', ''));
        const rateB = parseFloat(b.conversionRate.replace('%', ''));
        return rateA - rateB;
      },
      render: (text: string) => <span style={{ color: parseFloat(text) > 50 ? '#52c41a' : '#f5222d' }}>{text}</span>,
    },
  ];

  // 加载招聘计划转化率数据
  const fetchRecruitStats = async () => {
    setLoading(true);
    try {
      let response;
      const params = {
        page: recruitPage,
        pageSize: recruitPageSize
      };

      if (planType && planId) {
        response = await getRecruitStatisticsByPlanId(planId, { ...params, planType });
      } else if (planType) {
        response = await getRecruitStatisticsByType(planType, params);
      } else if (planId) {
        response = await getRecruitStatisticsByPlanId(planId, params);
      } else {
        response = await getRecruitStatistics(params);
      }

      // 处理响应数据
      if (response.code === 1) {
        if (response.data) {
          let filteredData = response.data.row || [];
          
          // 如果有搜索关键字，进行本地过滤
          if (searchText) {
            const lowerSearchText = searchText.toLowerCase();
            filteredData = filteredData.filter((item: RecruitStatisticsItem) => 
              item.planName.toLowerCase().includes(lowerSearchText)
            );
          }
          
          setRecruitStats(filteredData);
          setRecruitTotal(searchText ? filteredData.length : (response.data.total || 0));
          
          // 如果没有数据，显示提示信息
          if (filteredData.length === 0) {
            message.info('暂无招聘计划转化率数据');
          }
        } else {
          setRecruitStats([]);
          setRecruitTotal(0);
          message.info('暂无招聘计划转化率数据');
        }
      } else {
        // 只有在确定不是"没有数据"的情况下才显示错误
        if (response.msg !== "没有数据" && response.data !== "没有数据") {
          message.error(response.msg || '获取招聘计划转化率统计失败');
        } else {
          setRecruitStats([]);
          setRecruitTotal(0);
          message.info('暂无招聘计划转化率数据');
        }
      }
    } catch (error: any) {
      console.error('获取招聘计划转化率统计失败:', error);
      setRecruitStats([]);
      setRecruitTotal(0);
      
      // 只有在确定不是"没有数据"的情况下才显示错误
      if (!error.message || !error.message.includes('没有数据')) {
        message.error('获取招聘计划转化率统计失败: ' + (error.message || '未知错误'));
      } else {
        message.info('暂无招聘计划转化率数据');
      }
    } finally {
      setLoading(false);
    }
  };

  // 加载面试通过率数据
  const fetchInterviewStats = async () => {
    setLoading(true);
    try {
      let response;
      const params: any = {
        page: interviewPage,
        pageSize: interviewPageSize
      };

      // 添加筛选条件
      if (planType) params.planType = planType;
      if (planId) params.planId = planId;
      if (interviewId) params.interviewId = interviewId;
      if (deptId) params.deptId = deptId;
      if (positionNumber) params.positionNumber = positionNumber;

      response = await getInterviewStatistics(params);

      // 处理响应数据
      if (response.code === 1) {
        if (response.data) {
          let filteredData = response.data.row || [];
          
          // 如果有搜索关键字，进行本地过滤
          if (searchText) {
            const lowerSearchText = searchText.toLowerCase();
            filteredData = filteredData.filter((item: InterviewStatisticsItem) => 
              item.interviewName.toLowerCase().includes(lowerSearchText)
            );
          }
          
          setInterviewStats(filteredData);
          setInterviewTotal(searchText ? filteredData.length : (response.data.total || 0));
          
          // 如果没有数据，显示提示信息
          if (filteredData.length === 0) {
            message.info('暂无面试通过率数据');
          }
        } else {
          setInterviewStats([]);
          setInterviewTotal(0);
          message.info('暂无面试通过率数据');
        }
      } else {
        // 只有在确定不是"没有数据"的情况下才显示错误
        if (response.msg !== "没有数据" && response.data !== "没有数据") {
          message.error(response.msg || '获取面试通过率统计失败');
        } else {
          setInterviewStats([]);
          setInterviewTotal(0);
          message.info('暂无面试通过率数据');
        }
      }
    } catch (error: any) {
      console.error('获取面试通过率统计失败:', error);
      setInterviewStats([]);
      setInterviewTotal(0);
      
      // 只有在确定不是"没有数据"的情况下才显示错误
      if (!error.message || !error.message.includes('没有数据')) {
        message.error('获取面试通过率统计失败: ' + (error.message || '未知错误'));
      } else {
        message.info('暂无面试通过率数据');
      }
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索
  const handleSearch = () => {
    if (activeTab === 'recruitRate') {
      setRecruitPage(1);
      fetchRecruitStats();
    } else {
      setInterviewPage(1);
      fetchInterviewStats();
    }
  };

  // 处理重置
  const handleReset = () => {
    setPlanType(undefined);
    setPlanId(undefined);
    setInterviewId(undefined);
    setDeptId(undefined);
    setPositionNumber(undefined);
    setSearchText('');
    
    // 重置后自动刷新数据
    if (activeTab === 'recruitRate') {
      setRecruitPage(1);
      setRecruitPageSize(10);
      setTimeout(() => {
        fetchRecruitStats();
      }, 0);
    } else {
      setInterviewPage(1);
      setInterviewPageSize(10);
      setTimeout(() => {
        fetchInterviewStats();
      }, 0);
    }
  };

  // 处理标签页切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    if (key === 'recruitRate') {
      fetchRecruitStats();
    } else {
      fetchInterviewStats();
    }
  };

  // 处理招聘计划转化率分页变化
  const handleRecruitPageChange = (page: number, pageSize: number) => {
    setRecruitPage(page);
    setRecruitPageSize(pageSize);
  };

  // 处理面试通过率分页变化
  const handleInterviewPageChange = (page: number, pageSize: number) => {
    setInterviewPage(page);
    setInterviewPageSize(pageSize);
  };

  // 监听分页变化，重新加载数据
  useEffect(() => {
    if (activeTab === 'recruitRate') {
      fetchRecruitStats();
    }
  }, [recruitPage, recruitPageSize]);

  useEffect(() => {
    if (activeTab === 'interviewRate') {
      fetchInterviewStats();
    }
  }, [interviewPage, interviewPageSize]);

  // 初始加载
  useEffect(() => {
    fetchRecruitStats();
  }, []);

  // 添加导出报表函数
  const exportToExcel = () => {
    try {
      // 根据当前活动标签页选择要导出的数据
      if (activeTab === 'recruitRate') {
        // 招聘计划转化率数据
        if (!recruitStats || recruitStats.length === 0) {
          message.warning('没有可导出的数据');
          return;
        }
        
        const fileName = '招聘计划转化率报表.xlsx';
        
        // 添加表头
        const worksheetData = [
          [
            '计划ID', 
            '计划名称', 
            '申请人数', 
            '通过人数', 
            '转化率(%)'
          ]
        ];
        
        // 添加数据行
        recruitStats.forEach((item) => {
          const conversionRate = item.allApplicantNumber > 0 
            ? ((item.allThroughNumber / item.allApplicantNumber) * 100).toFixed(2) 
            : '0.00';
          
          worksheetData.push([
            String(item.planId),
            item.planName,
            String(item.allApplicantNumber),
            String(item.allThroughNumber),
            conversionRate
          ]);
        });
        
        // 创建工作簿和工作表
        const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '招聘计划转化率');
        
        // 设置列宽
        const columnWidths = [
          { wch: 10 }, // 计划ID
          { wch: 25 }, // 计划名称
          { wch: 10 }, // 申请人数
          { wch: 10 }, // 通过人数
          { wch: 10 }  // 转化率
        ];
        
        worksheet['!cols'] = columnWidths;
        
        // 导出文件
        XLSX.writeFile(workbook, fileName);
        
        message.success('成功导出招聘计划转化率报表');
      } else {
        // 面试通过率数据
        if (!interviewStats || interviewStats.length === 0) {
          message.warning('没有可导出的数据');
          return;
        }
        
        const fileName = '面试通过率报表.xlsx';
        
        // 添加表头
        const worksheetData = [
          [
            '面试ID', 
            '面试名称', 
            '申请人数', 
            '通过人数', 
            '通过率(%)'
          ]
        ];
        
        // 添加数据行
        interviewStats.forEach((item) => {
          const passRate = item.applicantNumber > 0 
            ? ((item.throughNumber / item.applicantNumber) * 100).toFixed(2) 
            : '0.00';
            
          worksheetData.push([
            String(item.interviewId),
            item.interviewName,
            String(item.applicantNumber),
            String(item.throughNumber),
            passRate
          ]);
        });
        
        // 创建工作簿和工作表
        const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '面试通过率');
        
        // 设置列宽
        const columnWidths = [
          { wch: 10 }, // 面试ID
          { wch: 25 }, // 面试名称
          { wch: 10 }, // 申请人数
          { wch: 10 }, // 通过人数
          { wch: 10 }  // 通过率
        ];
        
        worksheet['!cols'] = columnWidths;
        
        // 导出文件
        XLSX.writeFile(workbook, fileName);
        
        message.success('成功导出面试通过率报表');
      }
    } catch (error) {
      console.error('导出报表失败:', error);
      message.error('导出报表失败，请稍后重试');
    }
  };

  // 渲染搜索表单
  const renderSearchForm = () => (
    <Card style={{ marginBottom: 16 }}>
      <Row gutter={16}>
        {activeTab === 'recruitRate' ? (
          // 招聘计划转化率筛选条件
          <>
            <Col xs={24} sm={12} md={6} lg={6}>
              <Select
                placeholder="选择计划类型"
                style={{ width: '100%' }}
                allowClear
                onChange={(value) => setPlanType(value)}
                value={planType}
              >
                <Option value={1}>管理岗位</Option>
                <Option value={2}>专任教师</Option>
                <Option value={3}>其他岗位</Option>
              </Select>
            </Col>
            <Col xs={24} sm={12} md={6} lg={6}>
              <Input
                placeholder="输入计划ID"
                value={planId}
                onChange={(e) => {
                  const value = e.target.value;
                  if (value === '') {
                    setPlanId(undefined);
                  } else if (!isNaN(Number(value))) {
                    setPlanId(Number(value));
                  }
                }}
              />
            </Col>
            <Col xs={24} sm={12} md={6} lg={6}>
              <Input
                placeholder="搜索计划名称"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                suffix={
                  <Tooltip title="输入关键字搜索计划名称">
                    <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)' }} />
                  </Tooltip>
                }
              />
            </Col>
          </>
        ) : (
          // 面试通过率筛选条件
          <>
            <Col xs={24} sm={12} md={4} lg={4}>
              <Select
                placeholder="选择计划类型"
                style={{ width: '100%' }}
                allowClear
                onChange={(value) => setPlanType(value)}
                value={planType}
              >
                <Option value={1}>管理岗位</Option>
                <Option value={2}>专任教师</Option>
                <Option value={3}>其他岗位</Option>
              </Select>
            </Col>
            <Col xs={24} sm={12} md={4} lg={4}>
              <Input
                placeholder="输入计划ID"
                value={planId}
                onChange={(e) => {
                  const value = e.target.value;
                  if (value === '') {
                    setPlanId(undefined);
                  } else if (!isNaN(Number(value))) {
                    setPlanId(Number(value));
                  }
                }}
              />
            </Col>
            <Col xs={24} sm={12} md={4} lg={4}>
              <Input
                placeholder="输入面试ID"
                value={interviewId}
                onChange={(e) => {
                  const value = e.target.value;
                  if (value === '') {
                    setInterviewId(undefined);
                  } else if (!isNaN(Number(value))) {
                    setInterviewId(Number(value));
                  }
                }}
              />
            </Col>
            <Col xs={24} sm={12} md={4} lg={4}>
              <Input
                placeholder="输入部门编号"
                value={deptId}
                onChange={(e) => setDeptId(e.target.value || undefined)}
              />
            </Col>
            <Col xs={24} sm={12} md={4} lg={4}>
              <Input
                placeholder="输入岗位编号"
                value={positionNumber}
                onChange={(e) => setPositionNumber(e.target.value || undefined)}
              />
            </Col>
            <Col xs={24} sm={12} md={4} lg={4}>
              <Input
                placeholder="搜索面试名称"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                suffix={
                  <Tooltip title="输入关键字搜索面试名称">
                    <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)' }} />
                  </Tooltip>
                }
              />
            </Col>
          </>
        )}
        <Col xs={24} sm={24} md={activeTab === 'recruitRate' ? 6 : 24} lg={activeTab === 'recruitRate' ? 6 : 24} style={{ textAlign: 'right', marginTop: activeTab === 'interviewRate' ? 16 : 0 }}>
          <Button 
            type="primary" 
            icon={<SearchOutlined />} 
            onClick={handleSearch}
            style={{ marginRight: 8 }}
          >
            搜索
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleReset}
            style={{ marginRight: 8 }}
          >
            重置
          </Button>
        </Col>
      </Row>
    </Card>
  );

  // 渲染统计摘要
  const renderSummary = () => {
    if (activeTab === 'recruitRate' && recruitStats.length > 0) {
      const totalRecruits = recruitStats.reduce((sum, item) => sum + item.allRecruitsNumber, 0);
      const totalApplicants = recruitStats.reduce((sum, item) => sum + item.allApplicantNumber, 0);
      const totalThrough = recruitStats.reduce((sum, item) => sum + item.allThroughNumber, 0);
      const avgConversionRate = totalApplicants > 0 ? ((totalThrough / totalApplicants) * 100).toFixed(2) + '%' : '0%';

      return (
        <Card style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic title="总招聘人数" value={totalRecruits} />
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic title="总申请人数" value={totalApplicants} />
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic title="总通过人数" value={totalThrough} />
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic 
                  title="平均转化率" 
                  value={avgConversionRate} 
                  valueStyle={{ color: parseFloat(avgConversionRate) > 50 ? '#52c41a' : '#f5222d' }}
                />
              </Card>
            </Col>
          </Row>
        </Card>
      );
    } else if (activeTab === 'interviewRate' && interviewStats.length > 0) {
      const totalRecruits = interviewStats.reduce((sum, item) => sum + item.recruitsNumber, 0);
      const totalApplicants = interviewStats.reduce((sum, item) => sum + item.applicantNumber, 0);
      const totalThrough = interviewStats.reduce((sum, item) => sum + item.throughNumber, 0);
      const avgConversionRate = totalApplicants > 0 ? ((totalThrough / totalApplicants) * 100).toFixed(2) + '%' : '0%';

      return (
        <Card style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic title="总招聘人数" value={totalRecruits} />
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic title="总申请人数" value={totalApplicants} />
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic title="总通过人数" value={totalThrough} />
              </Card>
            </Col>
            <Col span={6}>
              <Card bordered={false}>
                <Statistic 
                  title="平均转化率" 
                  value={avgConversionRate} 
                  valueStyle={{ color: parseFloat(avgConversionRate) > 50 ? '#52c41a' : '#f5222d' }}
                />
              </Card>
            </Col>
          </Row>
        </Card>
      );
    }

    return null;
  };

  // 渲染招聘计划转化率饼图
  const renderRecruitPieChart = () => {
    if (!recruitStats || recruitStats.length === 0) return null;

    // 计算总申请人数和总通过人数
    const totalApplicants = recruitStats.reduce((sum, item) => sum + item.allApplicantNumber, 0);
    const totalThrough = recruitStats.reduce((sum, item) => sum + item.allThroughNumber, 0);
    const totalRejected = totalApplicants - totalThrough;

    // 重新定义选项，避免重复属性
    const pieOption: EChartsOption = {
      title: {
        text: '招聘计划申请结果分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['通过人数', '未通过人数']
      },
      series: [
        {
          name: '申请结果',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: totalThrough, name: '通过人数', itemStyle: { color: '#52c41a' } },
            { value: totalRejected, name: '未通过人数', itemStyle: { color: '#f5222d' } }
          ]
        }
      ]
    };

    return (
      <Card title="申请结果分布" style={{ marginBottom: 16 }}>
        <ReactECharts option={pieOption} style={{ height: 300 }} />
      </Card>
    );
  };

  // 修改招聘计划转化率柱状图
  const renderRecruitBarChart = () => {
    if (!recruitStats || recruitStats.length === 0) return null;

    // 只取前5个计划，避免图表过于拥挤
    const topPlans = [...recruitStats].sort((a, b) => b.allApplicantNumber - a.allApplicantNumber).slice(0, 5);

    const barOption: EChartsOption = {
      title: {
        text: '招聘计划申请与通过情况(Top 5)',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['申请人数', '通过人数'],
        top: 'bottom'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: topPlans.map(plan => plan.planName)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '申请人数',
          type: 'bar',
          data: topPlans.map(plan => plan.allApplicantNumber)
        },
        {
          name: '通过人数',
          type: 'bar',
          data: topPlans.map(plan => plan.allThroughNumber)
        }
      ]
    };

    return (
      <Card title="招聘计划申请与通过情况" style={{ marginBottom: 16 }}>
        <ReactECharts option={barOption} style={{ height: 300 }} />
      </Card>
    );
  };

  // 修改面试通过率饼图
  const renderInterviewPieChart = () => {
    if (!interviewStats || interviewStats.length === 0) return null;

    // 计算总申请人数和总通过人数
    const totalApplicants = interviewStats.reduce((sum, item) => sum + item.applicantNumber, 0);
    const totalThrough = interviewStats.reduce((sum, item) => sum + item.throughNumber, 0);
    const totalRejected = totalApplicants - totalThrough;

    const interviewPieOption: EChartsOption = {
      title: {
        text: '面试结果分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['通过人数', '未通过人数']
      },
      series: [
        {
          name: '面试结果',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: totalThrough, name: '通过人数', itemStyle: { color: '#52c41a' } },
            { value: totalRejected, name: '未通过人数', itemStyle: { color: '#f5222d' } }
          ]
        }
      ]
    };

    return (
      <Card title="面试结果分布" style={{ marginBottom: 16 }}>
        <ReactECharts option={interviewPieOption} style={{ height: 300 }} />
      </Card>
    );
  };

  // 修改面试通过率柱状图
  const renderInterviewBarChart = () => {
    if (!interviewStats || interviewStats.length === 0) return null;

    // 只取前5个面试，避免图表过于拥挤
    const topInterviews = [...interviewStats].sort((a, b) => b.applicantNumber - a.applicantNumber).slice(0, 5);

    const interviewBarOption: EChartsOption = {
      title: {
        text: '面试申请与通过情况(Top 5)',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['申请人数', '通过人数'],
        top: 'bottom'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: topInterviews.map(interview => interview.interviewName)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '申请人数',
          type: 'bar',
          data: topInterviews.map(interview => interview.applicantNumber)
        },
        {
          name: '通过人数',
          type: 'bar',
          data: topInterviews.map(interview => interview.throughNumber)
        }
      ]
    };

    return (
      <Card title="面试申请与通过情况" style={{ marginBottom: 16 }}>
        <ReactECharts option={interviewBarOption} style={{ height: 300 }} />
      </Card>
    );
  };

  return (
    <Layout>
      <Card title="招聘数据分析" extra={<Button type="primary" icon={<DownloadOutlined />} onClick={exportToExcel}>导出报表</Button>}>
        {renderSearchForm()}
        
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="招聘计划转化率" key="recruitRate">
            {renderSummary()}
            
            {/* 添加图表区域 */}
            <Row gutter={16}>
              <Col span={12}>
                {renderRecruitPieChart()}
              </Col>
              <Col span={12}>
                {renderRecruitBarChart()}
              </Col>
            </Row>
            
            <Table
              columns={recruitColumns}
              dataSource={recruitStats}
              rowKey="planId"
              loading={loading}
              pagination={{
                current: recruitPage,
                pageSize: recruitPageSize,
                total: recruitTotal,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
                onChange: handleRecruitPageChange,
                onShowSizeChange: handleRecruitPageChange,
              }}
              locale={{ emptyText: '暂无数据' }}
            />
          </TabPane>
          <TabPane tab="面试通过率" key="interviewRate">
            {renderSummary()}
            
            {/* 添加图表区域 */}
            <Row gutter={16}>
              <Col span={12}>
                {renderInterviewPieChart()}
              </Col>
              <Col span={12}>
                {renderInterviewBarChart()}
              </Col>
            </Row>
            
            <Table
              columns={interviewColumns}
              dataSource={interviewStats}
              rowKey="interviewId"
              loading={loading}
              pagination={{
                current: interviewPage,
                pageSize: interviewPageSize,
                total: interviewTotal,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
                onChange: handleInterviewPageChange,
                onShowSizeChange: handleInterviewPageChange,
              }}
              locale={{ emptyText: '暂无数据' }}
            />
          </TabPane>
        </Tabs>
      </Card>
    </Layout>
  );
};

// 统计卡片组件
interface StatisticProps {
  title: string;
  value: string | number;
  valueStyle?: React.CSSProperties;
}

const Statistic = ({ title, value, valueStyle = {} }: StatisticProps) => (
  <div>
    <Text type="secondary">{title}</Text>
    <div>
      <Title level={3} style={{ margin: '8px 0', ...valueStyle }}>{value}</Title>
    </div>
  </div>
);

export default RecruitmentAnalyticsPage;
